package com.erp.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.auth0.jwt.interfaces.DecodedJWT;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.UUID;

public class JwtUtil {

    private static final Logger logger = LoggerFactory.getLogger(JwtUtil.class);
    // 密钥
    public static final String SECRET = "ff82854752c9d95afb57290fd7b9025af9ff3ee416c889c3870beacc290ca249";

    //间隔时间 单位分钟
    public static final int INTERVAL = 360;

    //自动续签时间 单位分钟
    public static final int REFRESH_INTERVAL = 20;

    //生成token
    public static String createToken(Integer userID,Integer companyID,String role,String code) {
        Date latDate = new Date();
        Date expDate = new Date(latDate.getTime()+INTERVAL*60*1000);

        return JWT.create()
                .withJWTId(UUID.randomUUID().toString())
                .withIssuedAt(latDate) //jwt生成的时间
                .withExpiresAt(expDate)//jwt过期的时间
                .withClaim("userID", userID)//向jwt中添加数据，可以添加多个，可被调用多次
                .withClaim("companyID", companyID)
                .withClaim("role", role)
                .withClaim("code", code)
                .sign(Algorithm.HMAC256(SECRET));//添加签名
    }


    //    根据token验证是否有效
    public static boolean verifyToken(String token) {
        try{
            JWT.require(Algorithm.HMAC256(SECRET)).build().verify(token);
            return true;
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            return false;
        }
    }

    //检查token是否需要续期？
    public static boolean needFreshToken(String token){
        if(!verifyToken(token)){return false;}
        DecodedJWT jwt = JWT.decode(token);
        Date expDate = jwt.getExpiresAt();
        long have = expDate.getTime() - System.currentTimeMillis();
        return have < REFRESH_INTERVAL*60*1000;
    }

    //读取jwt中存储数据
    public static Integer getUserID(String token) {
        if(!verifyToken(token)) return null;
        return JWT.decode(token).getClaim("userID").asInt();
    }

    public static Integer getCompanyID(String token) {
        if(!verifyToken(token)) return null;
        return JWT.decode(token).getClaim("companyID").asInt();
    }

    public static String getRole(String token) {
        if(!verifyToken(token)) return null;
        return JWT.decode(token).getClaim("role").asString();
    }
    public static String getCode(String token) {
        if(!verifyToken(token)) return null;
        return JWT.decode(token).getClaim("code").asString();
    }
    //获取到期时间
    public static Date getExpires(String token) {
        if(!verifyToken(token)) return null;
        return JWT.decode(token).getExpiresAt();
    }
}
